<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>canvas 绘制图片</title>
</head>
<body>

    <canvas id="canvas" height="600" width="600"></canvas>
    

    <script>

        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');

        const image = new Image();
        image.src = './img/timg.jpg';

        // 单个帧的宽度和高度
        image.onload = function() {
            const oWidth = this.width;
            const oHeight = this.height;

            const aloneWidth = oWidth / 4;
            const aloneHeight = oHeight / 2;

            let i = 0, j = 0, handle;

            function play() {
                handle = setTimeout(play, 80);
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(image, i * aloneWidth, j * aloneHeight, aloneWidth, aloneHeight, 100, 100, aloneWidth, aloneHeight);
                if(i > 3) {
                    i = 0;
                    j += 1;
                    if(j > 1) {
                        j = 0;
                    }
                }
                i += 1;
            }

            handle = setTimeout(play, 80);
        }

    </script>
</body>
</html>